package com.wk.controller;

import com.wk.model.Msg;
import com.wk.service.CommentService;
import com.wk.service.DetailService;
import com.wk.service.ReadService;
import com.wk.service.UserService;
import com.wk.vo.Book;
import com.wk.vo.Chapters;
import com.wk.vo.Comment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Controller
public class DetailController {
    @Resource
    private DetailService detailService;
    @Resource
    private ReadService readService;
    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;

    @RequestMapping("details")
    @ResponseBody
    public Msg getDetail(@RequestParam("bookId") int bookId, @RequestParam("userId") int userId){
        try {
            HashMap<String, Object> result = new HashMap<>();
            Book book_detail = detailService.getBookDetail(bookId);
            List<Chapters> chapters = readService.getAllChapters(bookId);
            HashMap<String,Object> currentChapter = readService.getCurrentChapter(bookId, userId);
            List<Comment> comments = commentService.getAllComments(bookId);
            List<HashMap<String, String>> commentResult = new ArrayList<>();
            for (Comment comment : comments) {
                HashMap<String, String> commentItem = new HashMap<>();
                if (null != comment.getComment() && !"".equals(comment.getComment())){
                    commentItem.put("username", userService.getUsernameById(comment.getUserId()));
                    commentItem.put("comment", comment.getComment());
                    commentResult.add(commentItem);
                }
            }
//            System.out.println("book_detail:\n"+book_detail);
//            System.out.println("chapters:\n"+chapters);
//            System.out.println("currentChapter:\n"+currentChapter);
//            System.out.println("comments:\n"+comments);
            result.put("book_detail", book_detail);
            result.put("chapters", chapters);
            result.put("currentChapter", currentChapter);
            result.put("comments", commentResult);
            System.out.println(result);
            return new Msg("200", "查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Msg("400", "查询失败", "");
        }
    }

}
